/**
 * Copyright (c) 2006 RiseSoft Co.,Ltd  
 * $Header$
 */
package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.risesoft.risebi.collection.model.ConfigDefine;
import net.risesoft.risebi.collection.model.ConfigValue;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.ConfigDefineManager;
import net.risesoft.risebi.collection.service.ConfigValueManager;
import net.risesoft.risebi.collection.service.RoleManager;
import net.risesoft.risebi.collection.service.ServiceManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.struts2extension.Trimable;
import net.risesoft.risebi.commons.util.ExceptionUtil;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Namespace;

import com.opensymphony.xwork2.ActionInvocation;

/**
 *
 *
 * @author <a href="mailto: chenjian@risesoft.net">陈健</a>
 * @version $Revision$
 * 
 */
@Namespace("/admin/ConfigAction")
public class ConfigAction extends BaseAction implements Trimable {


    public ConfigAction()
    {
        json_roles = "[]";
        json_services = "[]";
        json_applications = "[]";
        configDefine = new ConfigDefine();
    }

    public String prepareConfigList()
        throws Exception
    {
        return "success";
    }

    public String prepareAddConfig()
        throws Exception
    {
        return "success";
    }

    public String prepareEditConfig()
        throws Exception
    {
        configDefine = (ConfigDefine)configDefineManager.getObject(ConfigDefine.class, node);
        return "success";
    }

    public String prepareConfigValueList()
        throws Exception
    {
        java.util.List list = new ArrayList();
        configDefine = (ConfigDefine)configDefineManager.getObject(ConfigDefine.class, node);
        configType = configDefine.getType().intValue();
        switch(configType)
        {
        case 1: // '\001'
            list = roleManager.find("from Role");
            json_roles = JSONUtil.getJsonString("include", "guid,name", list, new String[0]);
            break;

        case 2: // '\002'
            list = serviceManager.find("from Service");
            json_services = JSONUtil.getJsonString("include", "guid,name", list, new String[0]);
            break;

        case 3: // '\003'
            list = applicationManager.find("from Application");
            json_applications = JSONUtil.getJsonString("include", "guid,name", list, new String[0]);
            break;
        }
        return "success";
    }

    public String prepareConfigValueAddRole()
        throws Exception
    {
        return "success";
    }

    public String refreshJson()
        throws Exception
    {
        try
        {
            if("jsonConfigList".equalsIgnoreCase(whichJson))
            {
                Map map = new HashMap();
                int count = configDefineManager.getCount("select count(*) from ConfigDefine").intValue();
                java.util.List list = configDefineManager.find("from ConfigDefine order by tabIndex", start, limit);
                map.put("count", Integer.valueOf(count));
                map.put("list", list);
                json = JSONUtil.getJsonString("include", "list,count,guid,name,type,value,description,tabIndex", map, new String[0]);
            } else
            if("jsonConfigValueList".equalsIgnoreCase(whichJson))
            {
                configDefine = (ConfigDefine)configDefineManager.getObject(ConfigDefine.class, node);
                configType = configDefine.getType().intValue();
                java.util.List list = new ArrayList();
                switch(configType)
                {
                case 1: // '\001'
                    list = configValueManager.find((new StringBuilder("from ConfigValue t where t.configDefine.guid='")).append(node).append("' and t.roleGuid is not null").toString());
                    break;

                case 2: // '\002'
                    list = configValueManager.find((new StringBuilder("from ConfigValue t where t.configDefine.guid='")).append(node).append("' and t.serviceGuid is not null").toString());
                    break;

                case 3: // '\003'
                    list = configValueManager.find((new StringBuilder("from ConfigValue t where t.configDefine.guid='")).append(node).append("' and t.applicationGuid is not null").toString());
                    break;
                }
                json = JSONUtil.getJsonString("include", "guid,value,tabIndex,applicationGuid,serviceGuid,roleGuid", list, new String[0]);
            }
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            json = "[]";
        }
        return "ajax";
    }

    public String addConfigDefine()
        throws Exception
    {
        LazyDynaBean ldb = new LazyDynaBean();
        try
        {
            int count = configDefineManager.getCount((new StringBuilder("select count(*) from ConfigDefine t where t.name='")).append(configDefine.getName()).append("'").toString()).intValue();
            if(count > 0)
            {
                ldb.set("success", Boolean.valueOf(false));
                ldb.set("reason", (new StringBuilder("'")).append(configDefine.getName()).append("'\u5DF2\u7ECF\u6709\u76F8\u540C\u7684\u540D\u5B57\u5B58\u5728\uFF0C\u8BF7\u4FEE\u6539\u540E\u518D\u589E\u52A0").toString());
            } else
            {
                configDefine.setGuid((new GUID()).toString());
                configDefineManager.saveObject(configDefine);
                ldb.set("success", Boolean.valueOf(true));
                ldb.set("reason", "\u4FDD\u5B58\u6210\u529F!");
            }
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            ldb.set("success", Boolean.valueOf(false));
            ldb.set("reason", e.getMessage());
        }
        json = JSONObject.fromObject(ldb).toString();
        return "ajax";
    }

    public String editConfigDefine()
        throws Exception
    {
        LazyDynaBean ldb = new LazyDynaBean();
        try
        {
            int count = configDefineManager.getCount((new StringBuilder("select count(*) from ConfigDefine t where t.name='")).append(configDefine.getName()).append("' and t.guid !='").append(configDefine.getGuid()).append("'").toString()).intValue();
            if(count > 0)
            {
                ldb.set("success", Boolean.valueOf(false));
                ldb.set("reason", (new StringBuilder("'")).append(configDefine.getName()).append("'\u5DF2\u7ECF\u6709\u76F8\u540C\u7684\u540D\u5B57\u5B58\u5728\uFF0C\u8BF7\u4FEE\u6539\u540E\u518D\u589E\u52A0").toString());
            } else
            {
                configDefineManager.saveObject(configDefine);
                ldb.set("success", Boolean.valueOf(true));
                ldb.set("reason", "\u4FDD\u5B58\u6210\u529F!");
            }
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            ldb.set("success", Boolean.valueOf(false));
            ldb.set("reason", e.getMessage());
        }
        json = JSONObject.fromObject(ldb).toString();
        return "ajax";
    }

    public String saveConfigValue()
        throws Exception
    {
        configDefine = (ConfigDefine)configDefineManager.getObject(ConfigDefine.class, node);
        LazyDynaBean ldb = new LazyDynaBean();
        try
        {
            ConfigValue ConfigValueList[] = (ConfigValue[])JSONUtil.stringToArray(json, ConfigValue.class);
            ConfigValue aconfigvalue[];
            int j = (aconfigvalue = ConfigValueList).length;
            for(int i = 0; i < j; i++)
            {
                ConfigValue c = aconfigvalue[i];
                if(c.getGuid() == null || c.getGuid().trim().length() == 0 || c.getGuid().startsWith("NEW"))
                    c.setGuid((new GUID()).toString());
                c.setConfigDefine(configDefine);
                configValueManager.saveObject(c);
            }

            ldb.set("success", Boolean.valueOf(true));
            ldb.set("reason", "\u4FDD\u5B58\u6210\u529F!");
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            ldb.set("success", Boolean.valueOf(false));
            ldb.set("reason", e.getMessage());
        }
        json = JSONObject.fromObject(ldb).toString();
        return "ajax";
    }

    public String removeConfigDefine()
        throws Exception
    {
        LazyDynaBean ldb = new LazyDynaBean();
        try
        {
            configValueManager.execute((new StringBuilder("delete from ConfigValue t where t.configDefine.guid='")).append(node).append("'").toString());
            configDefineManager.removeObject(ConfigDefine.class, node);
            ldb.set("success", Boolean.valueOf(true));
            ldb.set("reason", "\u5220\u9664\u914D\u7F6E\u6210\u529F!");
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            ldb.set("success", Boolean.valueOf(false));
            ldb.set("reason", e.getMessage());
        }
        json = JSONObject.fromObject(ldb).toString();
        return "ajax";
    }

    public String removeServiceConfigValue()
        throws Exception
    {
        LazyDynaBean ldb = new LazyDynaBean();
        try
        {
            configValueManager.removeObject(ConfigValue.class, node);
            ldb.set("success", Boolean.valueOf(true));
            ldb.set("reason", "\u5220\u9664\u914D\u7F6E\u503C\u6210\u529F!");
        }
        catch(Exception e)
        {
            log.error(ExceptionUtil.transformException(e));
            ldb.set("success", Boolean.valueOf(false));
            ldb.set("reason", e.getMessage());
        }
        json = JSONObject.fromObject(ldb).toString();
        return "ajax";
    }

    public String getJson_applications()
    {
        return json_applications;
    }

    public void setJson_applications(String json_applications)
    {
        this.json_applications = json_applications;
    }

    public ConfigDefine getConfigDefine()
    {
        return configDefine;
    }

    public void setConfigDefine(ConfigDefine configDefine)
    {
        this.configDefine = configDefine;
    }

    public String getServiceGuid()
    {
        return serviceGuid;
    }

    public void setServiceGuid(String serviceGuid)
    {
        this.serviceGuid = serviceGuid;
    }

    public int getConfigType()
    {
        return configType;
    }

    public void setConfigType(int configType)
    {
        this.configType = configType;
    }

    public ConfigDefineManager getConfigDefineManager()
    {
        return configDefineManager;
    }

    public void setConfigDefineManager(ConfigDefineManager configDefineManager)
    {
        this.configDefineManager = configDefineManager;
    }

    public ConfigValueManager getConfigValueManager()
    {
        return configValueManager;
    }

    public void setConfigValueManager(ConfigValueManager configValueManager)
    {
        this.configValueManager = configValueManager;
    }

    public ServiceManager getServiceManager()
    {
        return serviceManager;
    }

    public void setServiceManager(ServiceManager serviceManager)
    {
        this.serviceManager = serviceManager;
    }

    public ApplicationManager getApplicationManager()
    {
        return applicationManager;
    }

    public void setApplicationManager(ApplicationManager applicationManager)
    {
        this.applicationManager = applicationManager;
    }

    public RoleManager getRoleManager()
    {
        return roleManager;
    }

    public void setRoleManager(RoleManager roleManager)
    {
        this.roleManager = roleManager;
    }

    public String getJson_roles()
    {
        return json_roles;
    }

    public void setJson_roles(String json_roles)
    {
        this.json_roles = json_roles;
    }

    public String getJson_services()
    {
        return json_services;
    }

    public void setJson_services(String json_services)
    {
        this.json_services = json_services;
    }

    private static final long serialVersionUID = -7075414214233924492L;
    private static Log log = LogFactory.getLog(ConfigAction.class);
    private String json_roles;
    private String json_services;
    private String json_applications;
    private String serviceGuid;
    private int configType;
    private ConfigDefine configDefine;
    private ConfigDefineManager configDefineManager;
    private ConfigValueManager configValueManager;
    private ServiceManager serviceManager;
    private ApplicationManager applicationManager;
    private RoleManager roleManager;
	@Override
	public void afterTrim(ActionInvocation arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preTrim(ActionInvocation arg0) {
		// TODO Auto-generated method stub
		return false;
	}


}
